<?php
namespace App\Admin\Controllers;

use App\Admin\Renderable\UsersTable;
use App\Models\SystemConfig;
use App\Models\User;
use Dcat\Admin\Form\NestedForm;
use Illuminate\Routing\Controller;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Support\Arr;
use Dcat\Admin\Form;
//use Dcat\Admin\Http\Controllers\AdminController;
//use Dcat\Admin\Widgets\Form;
//use App\Helper\NewUploadField;
use Dcat\Admin\Form\Field\UploadField;

class SystemConfigController extends Controller
{
    use UploadField;
    /**
     * 列出所有配置的表单内容（按照顺序依次）
     * 这个配置是可以扩展的，不过 name 和 method 要对应，并且 method 方法在控制器中存在
     */
    const CONFIG_TYPE = [
        'config_one' => [
            'name' => '配置表单-1',
            'method' => 'config_one',
        ],
        'config_two' => [
            'name' => '配置表单-2',
            'method' => 'config_two',
        ],
        // 可以新增配置项，新增完需要添加 method 方法才行
    ];

    /**
     *  配置首页
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $content->row(function (Row $row) {
            $type = request('type', 'config_one');
            $tab = new Tab();
            // 获取数据库存储对应配置的信息
            $configArr = json_decode(SystemConfig::query()->where('name', '=', $type)->value('value'), true);
            // 循环所有配置项
            foreach (self::CONFIG_TYPE as $k => $item) {
                if ($k === $type) {
                    $tab->add($item['name'], $this->{$item['method']}($configArr), true);
                } else {
                    $tab->addLink($item['name'], admin_route('system-configs.index', ['type' => $k]));
                }
            }
            $row->column(12, $tab->withCard());
        });

        return $content->header('配置管理');
    }

    /**
     * 第一个 form 表单
     * 方法名为了简单表示协程 config_one, 可替换为自己业务的名称，并在 self::CONFIG_TYPE 中的配置保持一致
     * @param $configArr
     * @return string
     */
    protected function config_one($configArr = [])
    {
        $form = new Form();
        $form->disableHeader(); // 隐藏 header
        $form->disableViewCheck();
        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableResetButton();
        $form->action(admin_route('system-configs.store'));    // 设置表单提交的方法地址

        // 单个写入框的配置
        $form->text('config_one.text', '标题')->required()->default(Arr::get($configArr, 'text'));
        $form->password('config_one.password', '密码')->required()->default(Arr::get($configArr, 'password'));
        $form->email('config_one.email', '邮箱')->default(Arr::get($configArr, 'email'));
        $form->mobile('config_one.mobile', '手机')->default(Arr::get($configArr, 'mobile'));
        $form->url('config_one.url', '网址')->default(Arr::get($configArr, 'url'));
        $form->ip('config_one.ip', 'ip地址')->default(Arr::get($configArr, 'ip'));
        $form->color('config_one.color', '颜色选择')->default(Arr::get($configArr, 'color'));
        $form->divider();   // 分割线
        $form->selectTable('config_one.select-table', '下拉表格')
            ->title('User')
            ->from(UsersTable::make())
            ->model(User::class, 'id', 'name')->default(Arr::get($configArr, 'select-table'));
        $form->multipleSelectTable('config_one.select-resource-multiple', '多选下拉表格')
            ->title('User')
            ->max(4)
            ->from(UsersTable::make())
            ->model(User::class, 'id', 'name')->default(Arr::get($configArr, 'select-resource-multiple'));
        $form->icon('config_one.icon', 'icon样式')->default(Arr::get($configArr, 'icon'));
        $form->rate('config_one.rate', 'rate比率')->default(Arr::get($configArr, 'rate'));
        $form->decimal('config_one.decimal', '金额')->default(Arr::get($configArr, 'decimal'));
        $form->number('config_one.number', '数字')->default(Arr::get($configArr, 'number'));
        $form->currency('config_one.currency', '美元')->default(Arr::get($configArr, 'currency'));
        $form->switch('config_one.switch', '开关')->default(1)->default(Arr::get($configArr, 'switch'));
        $form->divider();   // 分割线

        // 单个时间选择框的配置
        $form->date('config_one.date', '日期')->default(Arr::get($configArr, 'date'));
        $form->time('config_one.time', '时间')->default(Arr::get($configArr, 'time'));
        $form->datetime('config_one.datetime', '时分秒')->default(Arr::get($configArr, 'datetime'));

        // 区间时间选择框的配置
        $form->dateRange('config_one.date-start', 'config_one.date-end', '日期区间1')->default([
            'start' => Arr::get($configArr, 'date-start'),
            'end'   => Arr::get($configArr, 'date-end'),
        ]);
        $form->timeRange('config_one.time-start', 'config_one.time-end', '时间区间2')->default([
            'start' => Arr::get($configArr, 'time-start'),
            'end' => Arr::get($configArr, 'time-end'),
        ]);
        $form->datetimeRange('config_one.datetime-start', 'config_one.datetime-end', '时分秒区间3')->default([
            'start' => Arr::get($configArr, 'datetime-start'),
            'end' => Arr::get($configArr, 'datetime-end'),
        ]);

        // 文本域的配置
        $form->textarea('config_one.textarea', '文本域')->default(Arr::get($configArr, 'textarea'));
        $form->divider();

        // 二维数组的配置
        $form->table('config_one.table', function (NestedForm $table) {
            $table->text('key', '名字');
            $table->text('value', '分数');
            $table->text('desc', '说明');
        })->default(Arr::get($configArr, 'table'));
        return "<div style='padding:10px 8px'>{$form->render()}</div>";
    }

    /**
     * 第二个 form 表单
     * 方法名为了简单表示协程 config_two, 可替换为自己业务的名称，并在 self::CONFIG_TYPE 中的配置保持一致
     * @param $configArr
     * @return string
     */
    protected function config_two($configArr = [])
    {
        $form = new Form();
        $form->disableHeader(); // 隐藏 header
        $form->disableViewCheck();
        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableResetButton();
        $form->action(admin_route('system-configs.store'));    // 设置表单提交的方法地址
        $names = $this->createNames();  // 获取用户表名称 - 可以自己更换业务内容

        // 标签和单选多选下拉框的配置
        $form->tags('config_two.tag', '标签')->options($names)->default(Arr::get($configArr, 'tag'));
        $form->select('config_two.select', '单选下拉框')->options($names)->default(Arr::get($configArr, 'select'));
        $form->multipleSelect('config_two.multiple-select', '多选下拉选框')->options($names)->options($names)->default(Arr::get($configArr, 'multiple-select'));
        ;

        // 图片和文件上传的配置
        $form->image('config_two.image', '图片上传')->default(Arr::get($configArr, 'image'));
        $form->multipleFile('config_two.multiple-file', '多文件上传')->limit(3)->default(Arr::get($configArr, 'multiple-file'));

        // 单选多选按钮的配置
        $form->checkbox('config_two.checkbox', '多选盒子')->options(['GET', 'POST', 'PUT', 'DELETE'])->canCheckAll()->default(Arr::get($configArr, 'checkbox'));
        $form->radio('config_two.radio', '单选按钮')->options(['GET', 'POST', 'PUT', 'DELETE'])->default(Arr::get($configArr, 'radio'));

        // 菜单树的配置
        $menuModel = config('admin.database.menu_model');
        $menuModel = new $menuModel;
        $form->tree('config_two.tree', '选择数')
            ->setTitleColumn('title')
            ->nodes($menuModel->allNodes())->default(Arr::get($configArr, 'tree'));

        // 列表盒子的配置
        $form->listbox('config_two.listbox', '列表盒子')->options($names)->default(Arr::get($configArr, 'listbox'));
        $form->editor('config_two.editor', '编辑器')->default(Arr::get($configArr, 'editor'));
        return "<div style='padding:9px 8px'>{$form->render()}</div>";
    }

    /**
     * 生成用户数据
     * @return array
     */
    protected function createNames()
    {
        if (isset($this->names)) {
            return $this->names;
        }
        return User::query()->pluck('name')->toArray();
    }

    /**
     *  巡检配置提交
     * @return JsonResponse|mixed
     */
    public function store()
    {
        // 获取请求过来的值
        $request = request();
        if (empty($allData = $request->all())) {
            return JsonResponse::make()->error('没有数据提交！');
        }

        if ($request->hasFile('_file_')) {
            try {
                // 如果有图片传入 或者 如果有文件传入
                return $this->upload($request->file('_file_'));
            } catch (\Exception $e) {
                return JsonResponse::make()->error('上传失败：' . $e->getMessage());
            }
        }

        // 循环数据
        foreach ($allData as $k => $v) {
            if (!in_array($k, array_keys(self::CONFIG_TYPE))) {
                continue;
            }
            if (array_key_exists('editor', $v)) {
                $v['editor'] = htmlspecialchars($v['editor']);
            }
            SystemConfig::query()->updateOrCreate(['name' => $k], ['name' => $k, 'value' => json_encode($v)]);
        }
        return JsonResponse::make()->success('提交成功！')->refresh();
    }


    /**
     * Get field validation rules.
     *
     * @return string
     */
    protected function getRules()
    {
        return '';
    }

    /**
     * @return mixed
     */
    public function defaultDirectory()
    {
        return config('admin.upload.directory.file');
    }
}
